import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Dimensions, Alert } from "react-native";
import { style } from '../../theme/style';
import { Common } from '../../component/common/Common';
import { GLOBAL } from '../../config/global';
import ToastUtil from '../../utils/toast';
import PasswordGesture from 'react-native-gesture-password';
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';
import HTTP from '../../utils/http';
import ToastUtils from '../../utils/toast';
import { API, API_GENERATE } from '../../config/api';
import { StackActions, NavigationActions } from 'react-navigation';


const resetAction = StackActions.reset({
	index: 0,
	actions: [NavigationActions.navigate({ routeName: 'LoginPage' })],
});

const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;
export class gesturePassword extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      header: null,
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      message: '绘制解锁图案',
      isOpen:true
    };
    this.Password1 = ''
  }

  async	componentWillMount () {
    GLOBAL.BIND_GESTURE_PASSWORD = await StorageHelper.get(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD);
    console.log(GLOBAL.BIND_GESTURE_PASSWORD)
  }

  //初始函数
  _init = async () => {

  }
  reset = () => {
    this.Password1 = ''
    this.setState({
      status: 'normal',
      message: '绘制解锁图案'
    });
  }
  onEnd = (password) => {
    if(this.state.isOpen&&!GLOBAL.BIND_GESTURE_PASSWORD){
      if (this.Password1 === '') {
        // The first password
        if (password.length < 4) {
          this.setState({
            status: 'wrong',
            message: '最少链接四个点,请重新输入'
          });
        }
        else {
          this.Password1 = password;
          this.setState({
            status: 'normal',
            message: '再次绘制解锁图案'
          });
        }
      }
      else {
        // The second password
        if (password === this.Password1) {
          ToastUtil.showSuccess('设置成功').then(() => {
            //储存密码
            GLOBAL.BIND_GESTURE_PASSWORD = password
            StorageHelper.set(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD, GLOBAL.BIND_GESTURE_PASSWORD);
            GLOBAL.BIND_LOGIN_TYPE = 'GESTURE'
            StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
            this.props.navigation.navigate('HomePage');
          })
          this.Password1 = '';
          // your codes to close this view
        } else {
          this.setState({
            status: 'wrong',
            message: '与上一次绘制不一致，请重新绘制'
          });
        }
      }
    }
    else{
      if(password===GLOBAL.BIND_GESTURE_PASSWORD){
        ToastUtil.showSuccess('关闭成功').then(() => {
          //储存密码
          GLOBAL.BIND_GESTURE_PASSWORD = ''
          StorageHelper.set(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD, GLOBAL.BIND_GESTURE_PASSWORD);
          //判断开启时默认类型
          if(GLOBAL.BIND_BIOMETRY_AUTH){
            GLOBAL.BIND_LOGIN_TYPE = 'BIOMETRY'
          }
          else{
            GLOBAL.BIND_LOGIN_TYPE = ''
          }
          StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
          this.props.navigation.navigate('HomePage');
        })
      }
      else{
        this.setState({
          status: 'wrong',
          message: '密码错误'
        });
      }
    }
    
  }
  onStart = () => {
    if(this.state.isOpen){
      if (this.Password1 === '') {
        this.setState({
          status: 'normal',
          message: '绘制解锁图案'
        });
      } 
      else {
        this.setState({
          status: 'normal',
          message: '再次绘制解锁图案'
        });
      }
    }
    else{
      this.setState({
        status: 'normal',
        message: '请输入原手势密码'
      });
    }
  }

   logout =async () =>{
    GLOBAL.BIND_GESTURE_PASSWORD = ''
    StorageHelper.set(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD, GLOBAL.BIND_GESTURE_PASSWORD);
    if(GLOBAL.BIND_BIOMETRY_AUTH){
      GLOBAL.BIND_LOGIN_TYPE = 'BIOMETRY'
    }
    else{
      GLOBAL.BIND_LOGIN_TYPE = ''
    }
    StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
    await StorageHelper.multiRemove([
      STORAGE_CONSTANT.DICTIONARY,
      STORAGE_CONSTANT.VERSION_IGNORE,
      STORAGE_CONSTANT.TOKEN,
      STORAGE_CONSTANT.MODULE_VERSION,
      STORAGE_CONSTANT.CONST_INFO,
      STORAGE_CONSTANT.CONST_INFO_EXPIRE
    ])
    let res = await HTTP.POST(API_GENERATE(API.LOG_OUT));
    if (res) {
      GLOBAL.TOKEN = null;
      GLOBAL.LOGIN_NAME = null;
      ToastUtils.showInfo('正在退出...').then(() => {
        GLOBAL.ROOT_NAVIGATION.dispatch(resetAction);
      })
    }
  }
  render () {
    let color
    if (this.state.status === 'wrong') {
      color = '#D93609'
    }
    else if (this.state.status === 'right') {
      color = '#5FA8FC'
    }
    else {
      color = '#5FA8FC'
    }
    let {isOpen,status,message} = this.state
    return (
      <View style={{ flex: 1 }}>
        <View style={styles.headBox}>
          <View style={styles.topBox}>
            <Common type="headLeft" onPress={() => { this.props.navigation.goBack() }} color='#fff' />
            <Text style={styles.topTitle}>开通手势密码登入</Text>
            <View style={styles.rightBox}>
              {GLOBAL.BIND_GESTURE_PASSWORD?null:
                <Text style={styles.rightText} onPress={() => { this.reset() }}>重设</Text>
              }
            </View>
            
          </View>
        </View>
          {GLOBAL.BIND_GESTURE_PASSWORD&&isOpen?
            <View style={styles.closeBox}>
              <View style={styles.itemText}>
                <Text style={styles.itemTitle}>您已绑定，可立即关闭</Text>
              </View>
              <TouchableOpacity style={styles.itemCtn} onPress={() => {this.setState({isOpen:false,message:'请输入原手势密码'})}}>
                <Text style={styles.itemBtn}>
                    点击关闭
                </Text>
              </TouchableOpacity>
            </View>
          :<View>
          <View style={styles.messageStyle}>
            <Text style={[styles.messageText, { color: color }]}>{message}</Text>
          </View>
          <View style={{ height: 550 * scale,marginTop:35*scale }}>
            <PasswordGesture
              style={{ backgroundColor: '#fff' }}
              ref='pg'
              status={status}
              // message={message}
              onStart={() => this.onStart()}
              onEnd={(password) => this.onEnd(password)}
              interval={1000}
            />
          </View>
          {GLOBAL.BIND_GESTURE_PASSWORD?
            <TouchableOpacity  style={styles.bottomBox} onPress={() => { Alert.alert('提示', '忘记手势，可以使用其他登陆方式，同时原手势密码失效', [
              { text: '取消' },
              {
                text: '其他登陆方式', onPress: async () => {
                  this.logout()
                }
              },
            ]);}}>
            <Text style={styles.bottomText}>忘记手势？</Text>
          </TouchableOpacity>:null
          }
          </View>
          }
      </View>
    )
  }
}


const styles = StyleSheet.create({
  headBox: {
    width:'100%',
    paddingTop: 40 * scale,
    // height: 160 * scale,
    backgroundColor: style.color.themeColor,
    paddingBottom: 10 * scale,
    position: "absolute",
    top: 0*scale,
    zIndex: 9*scale
  },
  topTitle: {
    fontSize: 18 * scale,
    color: '#fff',
    fontWeight:'600'
  },
  topBox: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 18*scale
  },
  messageStyle: {
    width:'100%',
    // marginTop: 30 * scale,
    justifyContent: 'center',
    alignItems: 'center',
    position: "absolute",
    top: 150*scale,
    zIndex: 9*scale
  },
  messageText: {
    color: '#5FA8FC',
    fontSize: 14 * scale
  },
  rightBox: {
    width: 50 * scale,
    justifyContent: 'center',
    alignItems: 'center'
  },
  rightText: {
    color: '#fff',
    fontSize: 14 * scale
  },
  closeBox:{
    // backgroundColor:'red',
    marginTop:250*scale
  },
  itemText: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingTop: 40 * scale,
  },
  itemTitle: {
    fontSize: 16 * scale,
    color: '#000',
  },
  flexText: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 100 * scale,
    alignItems: 'center',
  },
  itemCtn: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 66 * scale,
    marginLeft: 20 * scale,
    marginRight: 20 * scale,
    paddingBottom: 20 * scale,
    paddingTop: 20 * scale,
    backgroundColor: '#0E7FFD',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: '#0E7FFD',
    borderRadius: 5 * scale,
  },
  itemBtn: {
    fontSize: 16 * scale,
    color: '#fff',
  },
  bottomBox:{
    marginTop:30*scale,
    justifyContent:"center",
    alignItems:'center',
  },
  bottomText:{
    color:'#0087FF',
  }
})